package at.codebase.db.dao;

import static at.codebase.db.OfyService.ofy;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import at.codebase.db.entities.EMessage;
import at.codebase.db.entities.EUser;

/**
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 *
 */
public class EMessageDao {

	/**
	 * Adds a new Message to the Database
	 * 
	 * ToDo List here:
	 * * Add to Database
	 * 
	 * @param new Message
	 */
	public static void addMessage(final EMessage message) {
		ofy().save().entity(message).now();
	}
	
	public static List<EMessage> getMessagesByAddressor(final Long userId){
		return ofy().load().type(EMessage.class).filter("addressor", EUser.key(userId)).list();
	}
	
	public static List<EMessage> getMessagesByRecipient(final Long userId){
		return ofy().load().type(EMessage.class).filter("recipient", EUser.key(userId)).list();
	}

	public static void markRead(ArrayList<Long> ids, Long userId) {
		Map<Long, EMessage> idMap = ofy().load().type(EMessage.class).ids(ids);
		for(EMessage message:idMap.values()){
			if(message.getRecipient().getKey().getId() == userId.longValue())
				message.setUnread(false);
		}
		ofy().save().entities(idMap.values());
	}

	public static void removeMessagesById(ArrayList<Long> messageIds) {
		ofy().delete().type(EMessage.class).ids(messageIds);
	}

}
